package com.ontimedo;

import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ToneGenerator;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.TimePicker.OnTimeChangedListener;

public class Ontimedo extends Activity {
    /** Called when the activity is first created. */
	
	 private MediaPlayer mMediaPlayer;
	 private MediaPlayer mMediaPlayer2;
	 boolean enable = true;
	 boolean vibratorEn = true;
	 int wait,mInit,mShut = 0;
	 int hInit = 6;
	 int hShut = 23;
	 int lasthour = 25;
	 static final int TIME_DIALOG_INIT = 0;
	 static final int TIME_DIALOG_SHUT = 1;
	 TimePicker tpInit,tpShut;
	 SeekBar seekbar1;
	 AudioManager audioManager;
	 public static final String PREFS_NAME = "MyPrefsFile";
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startService(new Intent(this,ServiceHourBeep.class));
        
        //== Preff
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        hInit = settings.getInt("hInit", 6);
        hShut = settings.getInt("hShut", 23);
        vibratorEn = settings.getBoolean("vibratorEn", true);
       
        seekbar1 = (SeekBar)findViewById(R.id.seekBar1);
        audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
     
        /*
         * Adjustment bar for the volume
         * SEEK BAR - 
         */
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekbar1.setMax(maxVolume);
        seekbar1.setProgress(curVolume);
        seekbar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

		    @Override
		    public void onStopTrackingTouch(SeekBar arg0) {
		     // TODO Auto-generated method stub
		    	playAudio();
		    }
		
		    @Override
		    public void onStartTrackingTouch(SeekBar arg0) {
		     // TODO Auto-generated method stub
		
		    }
		
		    @Override
		    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
		     // TODO Auto-generated method stub
		     audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
		    }
        });
        
        /*
         * TOGGLE vibrator
         */
        final ToggleButton toggleVib = (ToggleButton)findViewById(R.id.toggleButton2);
        if(vibratorEn == false) toggleVib.setChecked(false);
        else toggleVib.setChecked(true);
        toggleVib.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                if(!(toggleVib.isChecked())){
                    vibratorEn = false;
                }
                else{
                	vibratorEn = true;
                }
            }
        });
        
        /*
         * TOGGLE ON/OFF Button
         */
        final ToggleButton toggle = (ToggleButton)findViewById(R.id.toggleButton1);
        toggle.setChecked(true);
        toggle.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                if(!(toggle.isChecked())){
                    enable = false;
                }
                else{
                	enable = true;
                }
            }
        });

        
        /*
         * "ENABLE" Time Picker
         */
       tpInit = (TimePicker)findViewById(R.id.tpInit);
       tpInit.setIs24HourView(true);
       tpInit.setCurrentHour(hInit);
       tpInit.setCurrentMinute(0);
        tpInit.setOnTimeChangedListener(new OnTimeChangedListener(){
        	public void onTimeChanged(TimePicker view, int hour, int minute){
        		if(hour >= hShut)  tpInit.setCurrentHour(hInit);
        		else hInit = hour;
        		
        	}

        });
      
        /*
         * "MUTE" Time Picker
         */
        tpShut = (TimePicker)findViewById(R.id.tpShut);
        tpShut.setIs24HourView(true);
        tpShut.setCurrentHour(hShut);
        tpShut.setCurrentMinute(0);
        tpShut.setOnTimeChangedListener(new OnTimeChangedListener(){
        	public void onTimeChanged(TimePicker view, int hour, int minute){
        		if(hour <= hInit)  tpShut.setCurrentHour(hShut);
        		else hShut = hour;
        		
        	}
        });
        
        
        /*
         * Thread and media player initalisation
         */
        Thread myThread = null;
        mMediaPlayer2 = MediaPlayer.create(this, R.raw.beep4);
        mMediaPlayer2.setLooping(false);        
        mMediaPlayer = MediaPlayer.create(this, R.raw.beep9);
        mMediaPlayer.setLooping(false);
        Runnable runnable = new CountDownRunner();
        myThread= new Thread(runnable);   
        myThread.start();     
        
        
         
    }
    
	@Override
	protected void onPause(){
		super.onStop();
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	    SharedPreferences.Editor editor = settings.edit();
	    editor.putInt("hInit", hInit);
	    editor.putInt("hShut", hShut);
	    editor.putBoolean("vibratorEn", vibratorEn);


	      // Commit the edits!
	      editor.commit();

	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	super.onCreateOptionsMenu(menu);
    	CreateMenu(menu);
    	return true;
    }
   
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	return MenuChoice();
    	
    }
   	private void CreateMenu(Menu menu)
   	{
   		MenuItem mnu1 = menu.add(0, 0, 0, "Comming soon!");
   		{	
   			mnu1.setAlphabeticShortcut('a');
   		}
   		
   	}
   	
   	private boolean MenuChoice ()
   	{
   		Toast.makeText(this, "Created by David Albertson", Toast.LENGTH_SHORT).show();   	
   		return true;
   	}
   	
    public void doWork() {

    	runOnUiThread(new Runnable() {
    	    public void run() {
    	        try{
    	        
    	        	Date dt = new Date();
    	        		int hours = dt.getHours();
    	                int minutes = dt.getMinutes();
    	                int seconds = dt.getSeconds();    	                
    	                startService(new Intent(getBaseContext(),ServiceHourBeep.class));
    	        		if((hours <= hShut && hours >= hInit) || (hShut == hInit))
    	        		{    	        			
    						if((minutes % 60 == 0) && (hours != lasthour) && ((seconds == 0) || (seconds == 1)))
    						{
    							playAudio();
    					        Toast toast = Toast.makeText(getBaseContext(), "Hourly reminder.", Toast.LENGTH_LONG);
    					        toast.show();
    					        lasthour = hours;
    						}    						
    	        		} 	        		
    	               
    	        }catch (Exception e) {
    	        	
    	        }
    	    }
    	});
    	

    	
 }

    
    /*
     * CONTROLS THE SLEEPING TIME OF THE THREAD
     */
    class CountDownRunner implements Runnable{
    	    // @Override
    	    public void run() {
    	            while(!Thread.currentThread().isInterrupted()){
    	                try {
    	                	
    	                doWork();
    	                Thread.sleep(1000);    	             
    	                
    	                
    	                } catch (InterruptedException e) {
    	                       
    	                }catch(Exception e){
    	                	
    	                }
    	            }
    	    }
    }
    
    
    /*
     * Calls the media player to play sound
     */
    private void playAudio () {
        try {
        
        	if(enable)
        	{

        		mMediaPlayer.seekTo(500);
        		mMediaPlayer.start();
        		
        		mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
        			public void onCompletion(MediaPlayer arg0) {
        				mMediaPlayer2.seekTo(300);
        				mMediaPlayer2.start();
        			}
        		});
        		
        		if(vibratorEn)
        		{
        		Vibrator vibrator = (Vibrator) getBaseContext().getSystemService(Context.VIBRATOR_SERVICE);
        		vibrator.vibrate(1000);
        		}

        	}
        	else
        	{
        		
        	}
        
        } catch (Exception e) {

        }
      }
}